package com.oodso.sell.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.oodso.sell.SellApplication;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * 项目名称：Sosoliuda
 * 类描述：
 * 创建人：周作威
 * 创建时间：2016/11/22
 */

public class DeviceInfoUtils {
    private static final String TAG = "DeviceInfoUtils.class";

    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    private static String getMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格  
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
        return macSerial;
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    /**
     * 获取设备IMEI
     *
     * @return
     */
    public static String getDeviceIMEI() {
        String imei = "";
        try {
            if (SellApplication.getInstance() != null) {
                TelephonyManager telephonyManager = (TelephonyManager) SellApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
                // 判断应用是否有权限
                imei = telephonyManager.getDeviceId();
                return TextUtils.isEmpty(imei) ? "" : imei;
            } else {
                return imei = "";
            }
        } catch (Exception e) {
            return imei = "";
        }
    }

    /**
     * 通过Api获取mac地址
     *
     * @return
     */
    public static String getMacAddress() {
        String macAddress = "";
        try {
            WifiManager wifiManager = (WifiManager) SellApplication.getInstance().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            macAddress = wifiInfo.getMacAddress();
            macAddress = macAddress.replace(":", "");
            macAddress = macAddress.trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(macAddress) || "0000000000000000".equals(macAddress)) {
            macAddress = getMac();
        }
        if (TextUtils.isEmpty(macAddress) || "0000000000000000".equals(macAddress)) {
            macAddress = getMacAddress2();
        }
        return macAddress;
    }

    // 安卓ID
    public static String getAndroid() {
        return android.provider.Settings.System.getString(SellApplication.getInstance().getContentResolver(), "android_id");
    }

    // 获取系统信息
    public static String getSerialnum() {
        String serialnum = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            serialnum = (String) (get.invoke(c, "ro.serialno", "unknown"));
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return serialnum;
    }

    /**
     * 调用Linux的busybox,这个需要设备支持busybox工具
     *
     * @return
     */
    private static String getMacAddress2() {
        String result = "";
        String Mac = "";
        result = callCmd("busybox ifconfig", "HWaddr");
        // 如果返回的result == null，则说明网络不可取
        if (result == null) {
            return "";
        }
        // 对该行数据进行解析
        // 例如：eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
        if (result.length() > 0 && result.contains("HWaddr") == true) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            if (Mac.length() > 1) {
                Mac = Mac.replaceAll(" ", "");
                result = "";
                String[] tmp = Mac.split(":");
                for (int i = 0; i < tmp.length; ++i) {
                    result += tmp[i];
                }
            }
        }
        return result;
    }

    private static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);
            // 执行命令cmd，只取结果中含有filter的这一行
            while ((line = br.readLine()) != null && line.contains(filter) == false) {
                // result += line;
            }
            result = line;
        } catch (Exception e) {
            e.printStackTrace();
            result = "";
        }
        return result;
    }

    /**
     * 获取sim卡信息 (1)有卡并且获取传手机号 (2)有卡获取不到传1 (3)无卡传-1
     *
     * @return
     */
    public static String getSIMCardInfo() {
        try {
            TelephonyManager telMgr = null;
            telMgr = (TelephonyManager) SellApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
            if (telMgr.getSimState() == TelephonyManager.SIM_STATE_READY) {
                if (!TextUtils.isEmpty(telMgr.getLine1Number())) {
                    // return telMgr.getLine1Number().length() < 5 ? "1" :
                    // telMgr.getLine1Number();
                    return "1";
                }
                return "1";
            } else if (telMgr.getSimState() == TelephonyManager.SIM_STATE_ABSENT) {
                // return "-1";
                return "0";
            }
        } catch (Exception e) {
            // return "-1";
            return "0";
        }
        // return "-1";
        return "0";
    }

    /**
     * 渠道号
     *
     * @return
     */
    public static String getChannel() {
        String channel = "ceshi";
        try {
            ApplicationInfo appInfo = SellApplication.getInstance().getPackageManager().getApplicationInfo(SellApplication.getInstance().getPackageName(), PackageManager.GET_META_DATA);
            channel = appInfo.metaData.getString("UMENG_CHANNEL");
            return channel;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return channel;
    }

    /**
     * 将网络类型
     *
     * @return
     */
    public static String getNetworkType() {
        String strNetworkType = "";
        NetworkInfo networkInfo = ((ConnectivityManager) SellApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();
                // TD-SCDMA networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: // api<8 : replace by
                        // 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: // api<9 : replace by
                        // 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: // api<11 : replace by
                        // 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: // api<13 : replace by
                        // 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE: // api<11 : replace by
                        // 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = "未知";
                        }

                        break;
                }
            }
        }
        return strNetworkType;
    }

    //查询版本
    public static int getAppVersionCode() {
        int versionName;
        try {
            // ---get the package info---  
            PackageManager pm = SellApplication.getInstance().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(SellApplication.getInstance().getPackageName(), 0);
            versionName = pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return versionName;
    }

    //查询版本
    public static String getAppVersionName() {
        String versionName;
        try {
            // ---get the package info---  
            PackageManager pm = SellApplication.getInstance().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(SellApplication.getInstance().getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0";
        }
        return versionName;
    }

    //获取系统版本号
    public static String getSDKVersion() {
        String sdkVersion = "";
        try {
            sdkVersion = android.os.Build.VERSION.RELEASE;
        } catch (NumberFormatException e) {
            sdkVersion = "";
        }
        return sdkVersion;
    }

    /**
     * 获取手机品牌
     */
    public static String getBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机型号
     */
    public static String getModle() {
        return android.os.Build.MODEL;
    }

    public static String getDeviceId() {
        String tmDevice, androidId;
        tmDevice = "" + getSerialnum();
        androidId = "" + getAndroid();
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32));
        LogUtils.e("deviceUuid", deviceUuid);
        return deviceUuid.toString();
    }
    public static String getClientInfo() {
        String c = "{\"device_name\"=\"" + DeviceInfoUtils.getBrand() + DeviceInfoUtils.getModle() + "\"}";
        try {
            return new JSONObject(c).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

